#include "stdafx.hpp"
#include "ColligereDiscogsDataImporter.hpp"
#include "ColligereSearchDiscogs.hpp"

void col::DiscogsDataImporter::Load ( const wxURI &rIn )
{
	get_webpage ( rIn, mRawHtmlData );
	
	if ( mRawHtmlData.empty() )
	{
		throw DataImporterError ( rIn, _("Unable to download collection.") );
	}

	wxString cur;
	size_t pos = 0;
	const wxString release ( "/release/" );
	pos = mRawHtmlData.find_first_of ( release, pos );
	while ( pos != wxString::npos )
	{
		const wxString release_id ( mRawHtmlData.substr 
			( pos + release.length() ).BeforeFirst('"') );
		if ( !release_id.empty() )
		{
			mParseResults.push_back ( SearchDiscogs::SearchResult ( empty_string, 
				wxString::Format ( "%s%s%s", SearchDiscogs::GetServerAddress(),
				release, release_id ) ) );
		}
		pos = mRawHtmlData.find ( release, pos + release.length() );
	}
}

void col::DiscogsDataImporter::Import ( DatabaseInterfaceBase &rDest )
{
	DataImporterEvent evt_import_start ( COLLIGERE_EVT_IMPORT_START, this );
	rDest.GetLayout()->ProcessEvent ( evt_import_start );

	foreach ( const SearchDiscogs::SearchResult &r, mParseResults )
	{
		try
		{
			Artist artist ( SearchDiscogs().DownloadResult(r) );
			// The country field in the Discogs release page is not the 
			// country of the artist but the country of the label 
			// (e.g. Century Media->Germany).
			artist.SetCountry ( empty_string );
			
			rDest.GetActive()->GetHandler()->AddItem ( artist );

			DataImporterEvent evt_item_imported ( COLLIGERE_EVT_ITEM_IMPORTED, 
				this, artist.GetLastChild() );
			rDest.GetLayout()->ProcessEvent ( evt_item_imported );
		}
		catch ( std::exception & ) 
		{ 
			DataImporterEvent evt_import_end ( COLLIGERE_EVT_IMPORT_END, this );
			rDest.GetLayout()->ProcessEvent ( evt_import_end );
			throw;
		}
	}
	DataImporterEvent evt_import_end ( COLLIGERE_EVT_IMPORT_END, this );
	rDest.GetLayout()->ProcessEvent ( evt_import_end );
}

wxUint32 col::DiscogsDataImporter::GetItemCount() const
{
	return mParseResults.size();
}